<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <template v-slot:before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template v-slot:after>
          <el-button size="small" type="info" @click="exportMutiDate">excel复杂表头导出</el-button>
          <el-button size="small" type="danger" @click="exportDate">excel导出</el-button>
          <el-button size="small" type="success" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button :disabled="!checkPermission('add-user')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" :data="list" border stripe>
          <el-table-column align="center" type="index" label="序号" sortable width="80" />
          <el-table-column prop="username" label="姓名" sortable />
          <el-table-column label="头像" align="center">
            <template slot-scope="{ row }">
              <img
                v-imageerror="require('@/assets/common/img.jpeg')"
                :src="row.staffPhoto"
                alt=""
                style="border-radio:50%; width:100px; height:100px; padding:10px"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatEmployment" sortable />
          <el-table-column prop="departmentName" label="部门" sortable />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable>
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="状态" sortable>
            <template slot-scope="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button :disabled="!checkPermission('del-user')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            layout="total, prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            :current-page.sync="page.page"
            @current-change="getEmployeeList"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 使用组件 -->
    <add-employee :show-dialog.sync="showDialog" />
    <!-- 分配角色的弹层组件 -->
    <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    <!-- 二维码弹层组件 -->
    <el-dialog title="图片二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
export default {
  components: { AddEmployee, AssignRole },
  data() {
    return {
      showCodeDialog: false,
      showDialog: false,
      showRoleDialog: false,
      loading: false,
      userId: null, // 记录当前点击id
      list: [], // 接数据的
      page: {
        page: 1, // 当前页码
        size: 10,
        total: 0 // 总数
      }
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除
    delEmployee(id) {
      this.$confirm('确定删除该用户').then(() => {
        return delEmployee(id)
      }).then(() => {
        this.getEmployeeList()
        this.$message.success('删除成功')
      })
    },
    // 显示二维码
    showQrCode(url) {
      if (url && url.trim()) {
        this.showCodeDialog = true
        // 页面的渲染是异步的！！！！ 页面变化不会立刻获得页面dom元素
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // nextTick总是会等到当前数据更新完毕 并且渲染完毕之后执行
          // 此时能保证一定会拿到dom、对象
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
        })
      } else {
        this.$message.warning('当前用户没有头像')
      }
    },
    // 点击角色
    async assignRole(id) {
      this.userId = id // 记录当前点击id
      // 立刻调用数据
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    },
    // 普通表头
    exportDate() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: this.formatJSON(headers, rows), // 具体数据 必填
          filename: '人力资源表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 复杂表头
    exportMutiDate() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: this.formatJSON(headers, rows), // 具体数据 必填
          filename: '人力资源表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']], // 复杂表头的部分,里面一个数组就是一个表头
          merges: ['A1:A2', 'B1:F1', 'G1:G2'] // 需要合并的部分
        })
      })
    },
    formatJSON(headers, rows) {
      return rows.map(item => {
        return Object.values(headers).map(key => {
          if (key === 'timeOfEntry' || key === 'correctionTime') {
            return formatDate(item[key])
          } else if (key === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(o => o.id === item[key])
            return obj ? obj.value : '未知'
          }
          return item[key]
        })
      })
    }
  }
}
</script>

<style>

</style>
